const fs = require('fs');
const path = require('path');

/**
 * 数据库配置验证脚本
 * 检查所有必需的文件和配置是否正确
 */
class ConfigValidator {
  constructor() {
    this.errors = [];
    this.warnings = [];
    this.projectRoot = path.resolve(__dirname, '..');
  }

  /**
   * 检查文件是否存在
   */
  checkFileExists(filePath, required = true) {
    const fullPath = path.join(this.projectRoot, filePath);
    const exists = fs.existsSync(fullPath);
    
    if (!exists && required) {
      this.errors.push(`必需文件缺失: ${filePath}`);
    } else if (!exists) {
      this.warnings.push(`可选文件缺失: ${filePath}`);
    }
    
    return exists;
  }

  /**
   * 检查目录是否存在
   */
  checkDirectoryExists(dirPath, required = true) {
    const fullPath = path.join(this.projectRoot, dirPath);
    const exists = fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory();
    
    if (!exists && required) {
      this.errors.push(`必需目录缺失: ${dirPath}`);
    } else if (!exists) {
      this.warnings.push(`可选目录缺失: ${dirPath}`);
    }
    
    return exists;
  }

  /**
   * 检查环境变量配置
   */
  checkEnvironmentConfig() {
    console.log('🔍 检查环境配置...');
    
    // 检查 .env 文件
    if (!this.checkFileExists('.env')) {
      this.errors.push('请创建 .env 文件并配置数据库连接信息');
      return;
    }

    // 读取并验证 .env 内容
    try {
      require('dotenv').config({ path: path.join(this.projectRoot, '.env') });
      
      const requiredEnvVars = [
        'DB_HOST',
        'DB_PORT', 
        'DB_NAME',
        'DB_USER',
        'DB_PASS',
        'JWT_SECRET'
      ];

      for (const envVar of requiredEnvVars) {
        if (!process.env[envVar]) {
          this.errors.push(`环境变量缺失: ${envVar}`);
        }
      }

      // 检查数据库配置合理性
      if (process.env.DB_PORT && isNaN(parseInt(process.env.DB_PORT))) {
        this.errors.push('DB_PORT 必须是数字');
      }

      if (process.env.JWT_SECRET && process.env.JWT_SECRET.length < 32) {
        this.warnings.push('JWT_SECRET 长度建议至少32个字符');
      }

    } catch (error) {
      this.errors.push(`读取 .env 文件失败: ${error.message}`);
    }
  }

  /**
   * 检查项目结构
   */
  checkProjectStructure() {
    console.log('📁 检查项目结构...');
    
    // 必需的目录
    const requiredDirs = [
      'dao',
      'dao/model',
      'services',
      'routes',
      'middleware',
      'utils',
      'scripts',
      'scripts/migrations'
    ];

    for (const dir of requiredDirs) {
      this.checkDirectoryExists(dir, true);
    }

    // 可选的目录
    const optionalDirs = [
      'uploads',
      'logs',
      'docs',
      'tests'
    ];

    for (const dir of optionalDirs) {
      this.checkDirectoryExists(dir, false);
    }
  }

  /**
   * 检查核心文件
   */
  checkCoreFiles() {
    console.log('📄 检查核心文件...');
    
    // 必需的核心文件
    const requiredFiles = [
      'package.json',
      'app.js',
      'bin/www',
      'dao/dbConnect.js',
      'dao/model/index.js',
      'dao/model/userModel.js',
      'dao/model/courseModel.js',
      'dao/model/evaluationModel.js'
    ];

    for (const file of requiredFiles) {
      this.checkFileExists(file, true);
    }

    // 检查路由文件
    const routeFiles = [
      'routes/auth.js',
      'routes/users.js',
      'routes/courses.js',
      'routes/detection.js',
      'routes/health.js'
    ];

    for (const file of routeFiles) {
      this.checkFileExists(file, true);
    }

    // 检查服务文件
    const serviceFiles = [
      'services/userServices.js',
      'services/courseServices.js',
      'services/evaluationServices.js'
    ];

    for (const file of serviceFiles) {
      this.checkFileExists(file, true);
    }

    // 检查DAO文件
    const daoFiles = [
      'dao/userDao.js',
      'dao/courseDao.js',
      'dao/evaluationDao.js'
    ];

    for (const file of daoFiles) {
      this.checkFileExists(file, true);
    }
  }

  /**
   * 检查数据库脚本
   */
  checkDatabaseScripts() {
    console.log('🗄️  检查数据库脚本...');
    
    const dbScripts = [
      'scripts/setup.js',
      'scripts/migrate.js',
      'scripts/seed.js',
      'scripts/initDatabase.js',
      'scripts/migrations/001_create_tables.js'
    ];

    for (const script of dbScripts) {
      this.checkFileExists(script, true);
    }
  }

  /**
   * 检查中间件和工具
   */
  checkMiddlewareAndUtils() {
    console.log('🔧 检查中间件和工具...');
    
    const middlewareFiles = [
      'middleware/auth.js',
      'middleware/errorHandler.js'
    ];

    for (const file of middlewareFiles) {
      this.checkFileExists(file, true);
    }

    const utilFiles = [
      'utils/response.js',
      'utils/auth.js',
      'utils/errors.js'
    ];

    for (const file of utilFiles) {
      this.checkFileExists(file, true);
    }
  }

  /**
   * 检查package.json配置
   */
  checkPackageConfig() {
    console.log('📦 检查package.json配置...');
    
    try {
      const packagePath = path.join(this.projectRoot, 'package.json');
      const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));

      // 检查必需的依赖
      const requiredDeps = [
        'express',
        'sequelize',
        'mysql2',
        'bcryptjs',
        'jsonwebtoken',
        'express-validator',
        'multer',
        'cors',
        'helmet',
        'dotenv'
      ];

      const dependencies = { ...packageJson.dependencies, ...packageJson.devDependencies };

      for (const dep of requiredDeps) {
        if (!dependencies[dep]) {
          this.errors.push(`缺少必需依赖: ${dep}`);
        }
      }

      // 检查脚本命令
      const requiredScripts = [
        'start',
        'db:setup',
        'db:migrate',
        'db:seed'
      ];

      for (const script of requiredScripts) {
        if (!packageJson.scripts || !packageJson.scripts[script]) {
          this.warnings.push(`建议添加脚本命令: ${script}`);
        }
      }

    } catch (error) {
      this.errors.push(`读取package.json失败: ${error.message}`);
    }
  }

  /**
   * 执行完整验证
   */
  async validate() {
    console.log('🔍 开始配置验证...');
    console.log('='.repeat(50));

    this.checkEnvironmentConfig();
    this.checkProjectStructure();
    this.checkCoreFiles();
    this.checkDatabaseScripts();
    this.checkMiddlewareAndUtils();
    this.checkPackageConfig();

    console.log('='.repeat(50));
    
    // 显示结果
    if (this.errors.length === 0 && this.warnings.length === 0) {
      console.log('✅ 所有配置检查通过！');
      console.log('');
      console.log('🚀 下一步操作:');
      console.log('   1. 安装依赖: npm install');
      console.log('   2. 设置数据库: npm run db:setup');
      console.log('   3. 启动应用: npm start');
      return true;
    }

    if (this.errors.length > 0) {
      console.log('❌ 发现配置错误:');
      this.errors.forEach(error => console.log(`   - ${error}`));
      console.log('');
    }

    if (this.warnings.length > 0) {
      console.log('⚠️  配置警告:');
      this.warnings.forEach(warning => console.log(`   - ${warning}`));
      console.log('');
    }

    if (this.errors.length > 0) {
      console.log('💡 请修复上述错误后重新运行验证');
      return false;
    } else {
      console.log('✅ 主要配置正确，可以继续设置');
      return true;
    }
  }

  /**
   * 生成配置报告
   */
  generateReport() {
    const report = {
      timestamp: new Date().toISOString(),
      status: this.errors.length === 0 ? 'PASS' : 'FAIL',
      errors: this.errors,
      warnings: this.warnings,
      summary: {
        totalErrors: this.errors.length,
        totalWarnings: this.warnings.length
      }
    };

    const reportPath = path.join(this.projectRoot, 'validation-report.json');
    fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
    console.log(`📊 验证报告已保存: ${reportPath}`);

    return report;
  }
}

/**
 * 命令行处理
 */
async function main() {
  const validator = new ConfigValidator();
  
  try {
    const isValid = await validator.validate();
    const report = validator.generateReport();
    
    process.exit(isValid ? 0 : 1);
    
  } catch (error) {
    console.error('💥 验证过程失败:', error.message);
    process.exit(1);
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  main();
}

module.exports = ConfigValidator;
